package com.zjlanyun.erp.rfid.m10.u8.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import com.zjlanyun.erp.Common;
import com.zjlanyun.erp.MainApplication;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.config.AppConfig;
import com.zjlanyun.erp.rfid.m10.u8.TextMoveLayout;
import com.zjlanyun.erp.rfid.m10.u8.reader.CMD;
import com.zjlanyun.erp.rfid.m10.u8.reader.model.ReaderSetting;
import com.zjlanyun.erp.rfid.m10.u8.reader.server.ReaderBase;
import com.zjlanyun.erp.rfid.m10.u8.reader.server.ReaderHelper;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.view.BaseSwipeBackActivity;

public class OutPowerActivity extends BaseSwipeBackActivity {

    private Button mSet;
    /**
     * 最小功率值
     */
    private int startDBM = 0;
    /**
     * 最大功率值
     */
    private int endDBM = 33;
    /**
     * 最大功率和最小功率之间的间隔
     */
    private int totalDBM = 0;
    /**
     * 屏幕宽度
     */
    private int screenWidth;


    private ViewGroup.LayoutParams layoutParams;
    /**
     * 自定义随着拖动条一起移动的控件
     */
    private TextMoveLayout mOutPowerTextLayout;
    /**
     * 随着进度条移动的功率
     */
    private TextView moveTextDBM;

    private SeekBar mOutPowerSeekBar;

    private ReaderHelper mReaderHelper;
    private ReaderBase mReader;

    private static ReaderSetting m_curReaderSetting;

    private LocalBroadcastManager lbm;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rfid_setting_out_power);
        ((MainApplication) getApplication()).addActivity(this);
        initBaseView();
        title.setText("功率设置");

        screenWidth = Common.getScrrenWidth(this);

        moveTextDBM = new TextView(this);
//		moveTextDBM.setBackgroundColor(Color.rgb(245, 245, 245));
        moveTextDBM.setTextColor(Color.rgb(0, 161, 229));
        moveTextDBM.setTextSize(16);
        layoutParams = new ViewGroup.LayoutParams(screenWidth, 40);
        mOutPowerTextLayout = (TextMoveLayout) findViewById(R.id.out_power_textLayout);
        mOutPowerTextLayout.addView(moveTextDBM, layoutParams);
        moveTextDBM.layout(0, 20, screenWidth, 80);

        mOutPowerSeekBar = (SeekBar) findViewById(R.id.out_power_seekBar);
        mOutPowerSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListenerImp());

        try {
            mReaderHelper = ReaderHelper.getDefaultHelper();
            mReader = mReaderHelper.getReader();
        } catch (Exception e) {
            e.printStackTrace();
        }

        m_curReaderSetting = mReaderHelper.getCurReaderSetting();

        mSet = (Button) findViewById(R.id.btn_set);
        //mGet = (TextView) findViewById(R.id.get);
        //mOutPowerText = (EditText) findViewById(R.id.out_power_text);
        mOutPowerSeekBar = (SeekBar) findViewById(R.id.out_power_seekBar);
        mOutPowerSeekBar.setMax(33);
        mSet.setOnClickListener(setOutPowerOnClickListener);

        //mGet.setOnClickListener(setOutPowerOnClickListener);
        lbm  = LocalBroadcastManager.getInstance(this);

        IntentFilter itent = new IntentFilter();
        itent.addAction(ReaderHelper.BROADCAST_WRITE_LOG);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_READER_SETTING);
        lbm.registerReceiver(mRecv, itent);
        mReader.getOutputPower(m_curReaderSetting.btReadId);
        updateView();

    }

    private final BroadcastReceiver mRecv = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_READER_SETTING)) {
                byte btCmd = intent.getByteExtra("cmd", (byte) 0x00);

                if (btCmd == CMD.GET_OUTPUT_POWER || btCmd == CMD.SET_OUTPUT_POWER) {
                    updateView();
                }
            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_WRITE_LOG)) {
            }
        }
    };

    private class OnSeekBarChangeListenerImp implements
            SeekBar.OnSeekBarChangeListener {

        // 触发操作，拖动
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            float value = ((float) screenWidth / (float) 30) * (float) 0.8;
            int moveStep = Math.round(value);
            moveTextDBM.setWidth(80);
            moveTextDBM.layout((int) (progress * moveStep), 20, screenWidth, 80);
            moveTextDBM.setText(progress + "dBm");
        }

        // 表示进度条刚开始拖动，开始拖动时候触发的操作
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        // 停止拖动时候
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    }

    private String getCheckDBM(Integer progress) {
        totalDBM = endDBM - startDBM;
        float power = progress * ((float) totalDBM / (float) 100);
        return Math.round(power) + "dBm";
    }

    public void updateView() {
        if (m_curReaderSetting.btAryOutputPower != null) {
            Intent intent = getIntent();
            String from = intent.getStringExtra("from");
            int powerValue;
            if (from != null) {
                powerValue = AppConfig.getInstance().getInt(from, 0);
                if (powerValue == 0) {
                    powerValue = m_curReaderSetting.btAryOutputPower[0] & 0xFF;
                }
            } else {
                powerValue = m_curReaderSetting.btAryOutputPower[0] & 0xFF;
            }
            moveTextDBM.setText(String.valueOf(powerValue + "dBm"));
            mOutPowerSeekBar.setProgress(powerValue);
        }
    }

    private OnClickListener setOutPowerOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            int id = arg0.getId();
            if (id == R.id.btn_set) {
                byte btOutputPower = 0x00;
                try {
                    String powerStr = moveTextDBM.getText().toString();
                    btOutputPower = (byte) Integer.parseInt(powerStr.subSequence(0, powerStr.indexOf("dBm")).toString());
                    System.out.println(btOutputPower);
                } catch (Exception e) {
                    ;
                }
                int ret = mReader.setOutputPower(m_curReaderSetting.btReadId, btOutputPower);
                if (ret == 0) {
                    m_curReaderSetting.btAryOutputPower = new byte[]{btOutputPower};
                    Intent intent = getIntent();
                    String from = intent.getStringExtra("from");
                    if (from != null) {
                        AppConfig.getInstance().putInt(from, (int) btOutputPower);
                    }
                    Toastor.getInstance().showShortToast(R.string.str_setting_out_power_success);
                } else {
                    Toastor.getInstance().showShortToast(R.string.str_setting_out_power_fail);
                }
            }
        }
    };
}
